package com.wty.swhn.wty.util;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.wty.swhn.wty.adapter.FaceAdapter;
import com.wty.swhn.wty.dao.FaceImageDao;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * edittext，聊天显示框里的表情缩小还原类
 * */
public class XMPPHelper {
	private static final String TAG="XMPPHelper";
	private FaceImageDao faceImageDao = new FaceImageDao();// 表情添加图上类
	private int mCurrentPage = 0;// 当前表情页
	private static final Pattern EMOTION_URL = Pattern.compile("\\[(\\S+?)\\]");//正则表达式

	public static void verifyJabberID(String jid)
			throws XXAdressMalformedException {
		if (jid != null) {
			Pattern p = Pattern
					.compile("(?i)[a-z0-9\\-_\\.]++@[a-z0-9\\-_]++(\\.[a-z0-9\\-_]++)++");
			Matcher m = p.matcher(jid);

			if (!m.matches()) {
				throw new XXAdressMalformedException(
						"Configured Jabber-ID is incorrect!");
			}
		} else {
			throw new XXAdressMalformedException("Jabber-ID wasn't set!");
		}
	}

	public static void verifyJabberID(Editable jid)
			throws XXAdressMalformedException {
		verifyJabberID(jid.toString());
	}

	public static int tryToParseInt(String value, int defVal) {
		int ret;
		try {
			ret = Integer.parseInt(value);
		} catch (NumberFormatException ne) {
			ret = defVal;
		}
		return ret;
	}

	public static int getEditTextColor(Context ctx) {
		TypedValue tv = new TypedValue();
		boolean found = ctx.getTheme().resolveAttribute(
				android.R.attr.editTextColor, tv, true);
		if (found) {
			// SDK 11+
			return ctx.getResources().getColor(tv.resourceId);
		} else {
			// SDK < 11
			return ctx.getResources().getColor(
					android.R.color.primary_text_light);
		}
	}

	public static String splitJidAndServer(String account) {
		if (!account.contains("@"))
			return account;
		String[] res = account.split("@");
		String userName = res[0];
		return userName;
	}

	
	
	/**
	 * 处理EditText中的表情显示
	 * */
	public GridView getGridView(final Context context,int i,final EditText editext,final List<String> mFaceMapKeys) {
		// TODO Auto-generated method stub
		GridView gridView = new GridView(context);
		gridView.setNumColumns(7);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setHorizontalSpacing(1); // 两列之间的边距
		gridView.setVerticalSpacing(1); // 两行之间的边距
		gridView.setGravity(Gravity.CENTER);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));// LayoutParms第一个参数为宽，第二个为高
		gridView.setAdapter(new FaceAdapter(context, i));
		gridView.setOnTouchListener(forbidenScroll());// 判断是滑动还是点击
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				Log.e(TAG, "item==" + position);
				if (position == faceImageDao.NUM) {
					Log.e(TAG, "item1==" + position);
					int selection = editext.getSelectionStart();// 获取光标位置
					String text = editext.getText().toString();
					if (selection > 0) {
						String text2 = text.substring(selection - 1);
						if ("]".equals(text2)) {
							int start = text.lastIndexOf("[");
							int end = selection;
							editext.getText().delete(start, end);// 删除光标前字符
							return;
						}
						editext.getText().delete(selection - 1, selection);
					}
				} else {
					Log.e(TAG, "item2==" + position);
					int count = mCurrentPage * faceImageDao.NUM + position;
					Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
							(Integer) faceImageDao.getFaceMap().values().toArray()[count]);
					if (bitmap != null) {
						int rawWidth = bitmap.getHeight();
						int rawheight = bitmap.getHeight();
						int newwidth = 60;
						int newheight = 60;
						// 计算绽放因子
						float width = ((float) newwidth) / rawWidth;
						float height = ((float) newheight) / rawheight;
						// 建立矩阵
						Matrix matrix = new Matrix();
						matrix.postScale(width, height);
						// 设置图片的旋转角度
						// matrix.postRotate(-30);
						// 设置图片的倾斜
						// matrix.postSkew(0.1f, 0.1f);
						// 将图片大小压缩
						// 压缩后图片的宽和高以及kB大小均会变化
						/*
						 * Bitmap.createBitmap(Bitmap source, int x, int y, int
						 * width, int height,Matrix m, boolean filter)
						 * 
						 * 最后一个：filter解释 true if the source should be filtered.
						 * Only applies if the matrix contains more than just
						 * translation.
						 * 当进行的不只是平移变换时，filter参数为true可以进行滤波处理，有助于改善新图像质量;flase时，
						 * 计算机不做过滤处理。
						 * 
						 * 图片裁剪，可用这个方法： Bitmap source：要从中截图的原始位图 int x: 起始x坐标
						 * int y：起始y坐标 int width： 要截的图的宽度 int height：要截的图的高度
						 */
						Bitmap newbitmap = Bitmap.createBitmap(bitmap, 0, 0, rawWidth, rawheight, matrix, true);
						ImageSpan span = new ImageSpan(context, newbitmap);
						String emojiStr = mFaceMapKeys.get(count);
						SpannableString spannedString = new SpannableString(emojiStr);
						// 包括内容不会扩大，只会包含起点和终点，长度绝对不能为0，如果被删除的所有它们涵盖文字也会自动从缓冲区中删除
						// mChatEditText.append(spannableString);
						spannedString.setSpan(span, emojiStr.indexOf("["), emojiStr.indexOf("]") + 1,
								SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
						editext.append(spannedString);
						Log.e(TAG, "spannedString=" + spannedString);

					} else {
						Log.e(TAG, "item3==" + position);
						String ori = editext.getText().toString();
						int index = editext.getSelectionStart();
						StringBuilder stringBuilder = new StringBuilder(ori);
						stringBuilder.insert(index, mFaceMapKeys.get(count));
						editext.setText(stringBuilder.toString());
						editext.setSelection(index + mFaceMapKeys.get(count).length());
					}
				}

			}
		});
		Log.e(TAG, "item4==");
		return gridView;
	}
	// 防止乱pageview乱滚动
	private OnTouchListener forbidenScroll() {
		// TODO Auto-generated method stub
		return new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					return true;
				}
				return false;
			}
		};
	}
	/**
	 * 处理字符串中的表情
	 * 
	 * @param context
	 * @param message
	 *            传入的需要处理的String
	 * @param small
	 *            是否需要小图片
	 * @return
	 */
	public static CharSequence convertNormalStringToSpannableString(
			Context context, String message, boolean small) {
		String hackTxt;
  		if (message.startsWith("[") && message.endsWith("]")) {
 			hackTxt = message + " ";
		} else {
			hackTxt = message;
		}
 		SpannableString value = SpannableString.valueOf(hackTxt); //SpannableString文本类，包含不可变的文本但可以用已有对象替换和分离。

		Matcher localMatcher = EMOTION_URL.matcher(value);//Matcher 一个Matcher对象是一个状态机器，它依据Pattern对象做为匹配模式对字符串展开匹配检查。
 		while (localMatcher.find()) {//尝试在目标字符串里查找下一个匹配子串
           			String str2 = localMatcher.group(0);//返回当前查找而获得的与组匹配的所有子串内容
			int k = localMatcher.start();//返回当前查找所获子串的开始字符在原目标字符串中的位置。
			int m = localMatcher.end();//返回当前匹配的子串的最后一个字符在原目标字符串中的索引位置 。 
			if (m - k < 8) {
				if (FaceImageDao.getFaceMap().containsKey(str2)) {
					int face =FaceImageDao.getFaceMap().get(str2);
					Bitmap bitmap = BitmapFactory.decodeResource(
							context.getResources(), face);
					if (bitmap != null) {
						if (small) {
							int rawHeigh = bitmap.getHeight();
							int rawWidth = bitmap.getHeight();
							int newHeight = 30;
							int newWidth = 30;
							// 计算缩放因子
							float heightScale = ((float) newHeight) / rawHeigh;
							float widthScale = ((float) newWidth) / rawWidth;
							// 新建立矩阵
							Matrix matrix = new Matrix();
							matrix.postScale(heightScale, widthScale);
							// 设置图片的旋转角度
							// matrix.postRotate(-30);
							// 设置图片的倾斜
							// matrix.postSkew(0.1f, 0.1f);
							// 将图片大小压缩
							// 压缩后图片的宽和高以及kB大小均会变化
							bitmap = Bitmap.createBitmap(bitmap, 0, 0,
									rawWidth, rawHeigh, matrix, true);
						}
						ImageSpan localImageSpan = new ImageSpan(context,
								bitmap, ImageSpan.ALIGN_BASELINE);
						value.setSpan(localImageSpan, k, m,
								Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					}
				}
			}
		}
		return value;
	}

}
